import './contextMenu'
import './postMessage'
import { EventType, origin } from '@shared/index'
import { sendMessage } from './postMessage'

function registerScript(tab: chrome.tabs.Tab) {
  chrome.scripting
    .executeScript({
      target: { tabId: tab?.id! },
      files: ['content.js']
    })
    .then(() => {
      // 建立通信凭证
      sendMessage(tab.id!, { type: EventType.CONNECT })
    })
}

chrome.tabs.onUpdated.addListener((tabId) => {
  chrome.tabs.get(tabId).then((tab) => {
    const { status, url } = tab
    if (status === 'complete' && url?.includes(origin)) {
      // 注册脚本
      registerScript(tab)
    }
  })
})
